package com.store.app.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.PayUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;

import org.json.JSONObject;

/**
 * 惠易定调native的支付页面
 *
 */
public class NativePayActivity extends BaseActivity implements IOnHttpListener {
    private String tid;
    private String payment_id;
    private String title;
    private String info;
    private String money;
    private NetRequest netRequest;
    //支付选择imgview
    private ImageView img1, img2, img3;

    //支付选择
    private RelativeLayout relat1, relat2, relat3;

    //提交
    private TextView tv_submit;

    //账户余额
    private TextView tv_yuer;


    //支付选择 1 余额 2支付宝 3微信
    private int pay_type = 1;

    private PayUtil payUtil;

    private String memberId;

    private String dataSource;//通过数据来源区分2.0. 3.0 ，为空默认是2.0
    private String return_url;//惠易定3.0才有
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        netRequest = new NetRequest(this);
        setContentView(R.layout.activity_native_pay);
        Log.v("zyl", "NativePayActivity onCreate");
        ExitApplication.getInstance().addActivity(this);
        initView();

        initListeners();

        getIntentData();
        money = MoneyUtil.formatMoney(money);

        Log.v("zyl","MainActivity.member_id:"+MainActivity.member_id);
        Log.v("zyl","memberId:"+memberId);
        if(MainActivity.member_id==null||!memberId.equals(MainActivity.member_id)){
            relat1.setVisibility(View.GONE);
            relat2.performClick();
        }
        if (pay_type == 1) {
            if(dataSource.equals("3")){
                Log.v("zyl","传递之前dlreturn_ur111l:"+return_url);
                payUtil = new PayUtil(tv_yuer, money, NativePayActivity.this, tid, payment_id, title, info, "SJLY_02", SettingData.default_seller_id, memberId, "DDLX_11",return_url);
            }else{
                payUtil = new PayUtil(tv_yuer, money, NativePayActivity.this, tid, payment_id, title, info, "SJLY_02", SettingData.default_seller_id, memberId, "DDLX_06","");
            }

        } else {
            if(dataSource.equals("3")){
                Log.v("zyl","传递之前dlreturn_ur22222:"+return_url);
                payUtil = new PayUtil(tv_yuer, money, NativePayActivity.this, tid, payment_id, title, info, "SJLY_02", SettingData.default_seller_id, memberId, "DDLX_11",return_url);
            }else{
                payUtil = new PayUtil(tv_yuer, money, NativePayActivity.this, tid, payment_id, title, info, "SJLY_02", SettingData.default_seller_id, memberId, "DDLX_06","");
            }

        }
    }


    private void initView() {
        img1 = (ImageView) findViewById(R.id.pay_check_1);
        img2 = (ImageView) findViewById(R.id.pay_check_2);
        img3 = (ImageView) findViewById(R.id.pay_check_3);

        relat1 = (RelativeLayout) findViewById(R.id.pay_relat1);
        relat2 = (RelativeLayout) findViewById(R.id.pay_relat2);
        relat3 = (RelativeLayout) findViewById(R.id.pay_relat3);

        tv_submit = (TextView) findViewById(R.id.submit);

        tv_yuer = (TextView) findViewById(R.id.yuer);
    }

    private void initListeners() {
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (pay_type == 1) {
                        if(0==Double.parseDouble(tv_yuer.getText().toString().replace("元",""))){
                        Toast.makeText(NativePayActivity.this, "零钱余额不足,请选择其他支付方式！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    showConfirmDialog("", "确定" + "支付" + money + "元 ?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            payUtil.startGetOrder(SettingData.PAYMENT_WAY_05);
                        }
                    });

                } else if (pay_type == 2) {
                    payUtil.startGetOrder(SettingData.PAYMENT_WAY_01);
                } else if (pay_type == 3) {
                    //微信支付
                    boolean ifInstall = Utils.isWXAppInstalledAndSupported(NativePayActivity.this);
                    if (ifInstall) {
                        payUtil.startGetOrder(SettingData.PAYMENT_WAY_02);
                    } else {
                        showToast("尚未安装微信,请检查您的手机");
                    }

                }
            }
        });
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        relat1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 1;
                img1.setBackgroundResource(R.drawable.pay_circle);
                img2.setBackgroundResource(R.drawable.pay_circle_gray);
                img3.setBackgroundResource(R.drawable.pay_circle_gray);

            }
        });
        relat2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 2;
                img1.setBackgroundResource(R.drawable.pay_circle_gray);
                img2.setBackgroundResource(R.drawable.pay_circle);
                img3.setBackgroundResource(R.drawable.pay_circle_gray);
            }
        });
        relat3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 3;
                img1.setBackgroundResource(R.drawable.pay_circle_gray);
                img2.setBackgroundResource(R.drawable.pay_circle_gray);
                img3.setBackgroundResource(R.drawable.pay_circle);
            }
        });

    }

    private void getIntentData() {
        Intent intent = getIntent();
        String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            Uri uri = intent.getData();
            if (uri != null) {
                tid = uri.getQueryParameter("tid");
                payment_id = uri.getQueryParameter("payment_id");
                title = uri.getQueryParameter("title");
                money = uri.getQueryParameter("money");
                memberId = uri.getQueryParameter("stores_id");
                dataSource = uri.getQueryParameter("dataSource");
                return_url = uri.getQueryParameter("return_url");
                if(dataSource==null){
                    dataSource ="";
                }
                if(return_url==null){
                    return_url="";
                }
                Log.v("zyl","tid:"+tid);
                Log.v("zyl","payment_id:"+payment_id);
                Log.v("zyl","title:"+title);
                Log.v("zyl","money:"+money);
                Log.v("zyl","memberId:"+memberId);
                Log.v("zyl","dataSource:"+dataSource);
                Log.v("zyl","return_url:"+return_url);
            }
        }

        if (TextUtils.isEmpty(MainActivity.user_token) || TextUtils.isEmpty(MainActivity.member_id)) {
            Intent intent2 = new Intent(NativePayActivity.this,MainActivity.class);
            startActivity(intent2);
            finish();
        }else{
            netRequest.requestQueryAccount(1);
        }

//       new  update_data().start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        dismissProgressDialog();
    }

    @Override
    public void onAfinalFail() {
        showToast("请检查本地网络！");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //查询余额
        if(requestId == 1){
            try{
            JSONObject jsonObject = new JSONObject(result);
             String cash_balance = jsonObject.getString("cash_balance");
                tv_yuer.setText(cash_balance + "元");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        showToast(msg);
    }

//    public class update_data extends Thread {
//
//        public void run() {
//            Log.v("zyl","店东的memberid："+MainActivity.member_id);
//            Log.v("zyl","惠一丁的member_id："+memberId);
//            try {
//                List<NameValuePair> params1 = new ArrayList<NameValuePair>();
//                params1.add(new BasicNameValuePair("app_token", MainActivity.app_token));
//                JSONObject paramsone1 = new JSONObject();
//                paramsone1.put("member_id", MainActivity.member_id);
//                params1.add(new BasicNameValuePair("params", paramsone1.toString()));
//                params1.add(new BasicNameValuePair("service", "finance.memberAssetFind"));
//                String sign1 = Submit.genPackageSign(params1);
//                params1.add(new BasicNameValuePair("sign", sign1));
//                JSONObject obj1 = Submit.submit(params1, Stores.http + "/openapi/finance");
//                String result1 = obj1.getString("rsp_code");
//                Log.v("zyl","查询结果："+obj1.toString());
//                if (result1.equals("succ")) {
//                    JSONObject data1 = obj1.getJSONObject("data");
//                    Log.v("zyl", "data1:" + data1);
//                    handler.obtainMessage(2,data1.getString("cash_balance")).sendToTarget();
//                } else {
//
////                    new  GoToLogin(NativePayActivity.this).setGoToLogin();
////                    finish();
//                    Log.v("zyl","obj1 msg:"+obj1.getString("error_msg"));
//                        handler.obtainMessage(1,"余额查询失败"+"===="+result1).sendToTarget();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                // TODO Auto-generated catch block
//                handler.obtainMessage(1,"余额查询失败Exception").sendToTarget();
//            }
//        }
//    }


    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    Toast.makeText(NativePayActivity.this,"余额查询失败",Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    String s_yuer = (String)msg.obj;
                    if (!TextUtils.isEmpty(s_yuer)) {
                        tv_yuer.setText(s_yuer + "元");
                    }
                    break;
            }
        }
    };

}
